package com.gen.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 响应头拦截器
 */
public class HttpResponseInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log = LoggerFactory.getLogger(HttpResponseInterceptor.class);

	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		try {
			// 被映射的方法
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			// 从HandlerMethod的注解中解析出响应头
			HttpResponseInterceptorAnnotation httpResponseInterceptorAnnotation = handlerMethod.getMethodAnnotation(HttpResponseInterceptorAnnotation.class);
			if (httpResponseInterceptorAnnotation != null) {
				String[] headers = httpResponseInterceptorAnnotation.headers();
				if (headers != null) {
					for (String header : headers) {
						String[] splitHeader = header.split(":");
						// 注入响应中
						response.setHeader(splitHeader[0], splitHeader[1]);
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
